﻿using System;
using System.Configuration;
using System.Reflection;
using PSE.Deployment.SetupBase.Configuration;

namespace PSE.Deployment.SetupBase
{
    public static class SetupMainFactory
    {
        private static readonly SetupMain Instance = CreateEngineProvider();

        public static SetupMain GetInstance()
        {
            return Instance;
        }

        public static T GetInstance<T>()
            where T : SetupMain
        {
            return (T)Instance;
        }

        static SetupMain CreateEngineProvider()
        {
            SetupConfigurationSection setupSection = System.Configuration.ConfigurationManager.GetSection("setupConfiguration") as SetupConfigurationSection;

            if (setupSection == null)
                throw new ConfigurationErrorsException("The section 'setupConfiguration' doesn't exist in the configuration file.");

            if (setupSection.SingletonProvider.Type == null)
                throw new ArgumentNullException("setupSection.SingletonProvider.Type");

            if (!setupSection.SingletonProvider.Type.IsSubclassOf(typeof(SetupMain)))
                throw new Exception("Invalid provider type. The provider must inherit from SetupMain.");

            SetupMain instance = null;

            try
            {
                instance = (SetupMain)Activator.CreateInstance(setupSection.SingletonProvider.Type);
            }
            catch (TargetInvocationException ex)
            {
                if (ex.InnerException != null)
                    throw ex.InnerException;
                else
                    throw;
            }
            catch
            {
                throw;
            }

            return instance;
        }
    }
}